#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>

#define MAX 1024
#define ARGC 64
#define SEP " "

int split(char *commandStr, char *argv[])
{
    assert(commandStr);
    assert(argv);

    argv[0] = strtok(commandStr, SEP);
    if (argv[0] == NULL)
        return -1;
    int i = 1;
    while ((argv[i++] = strtok(NULL, SEP)))
        ;
    return 0;
}

int main()
{
    while (1)
    {
        // [1]按行读取(fgets)用户的输入字符串
        char commandStr[MAX] = {0};
        char *argv[ARGC] = {NULL};
        printf("[Stephen@myMachine ~/Apath]$ ");
        fflush(stdout);
        char *s = fgets(commandStr, sizeof(commandStr), stdin);
        assert(s);
        (void)s;
        commandStr[strlen(commandStr) - 1] = '\0'; // 除去fgets都进来的\n

        // [2]处理用户输入的字符串，将其分割并存入字符指针数组里
        int n = split(commandStr, argv);
        if (n != 0)
            continue;

        // [3]创建子进程，让其程序替换exevp
        pid_t id = fork();
        assert(id >= 0);
        (void)id;
        if (id == 0)
        {
            // child
            execvp(argv[0], argv);
            exit(-1); // 程序替换失败
        }

        // parent
        //  [4]等待子进程
        int status = 0;
        waitpid(id, &status, 0);
    }
    return 0;
}